<template>
    <div>
        <el-button type="success" @click="openDialog('add')">新增</el-button>

        <span style="font-size: 20px; margin-left: 20px; font-weight: bold">工序分类列表</span>

        <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
        <!-- 工序分类列表（仅展示序号列相关结构） -->
        <div class="table-container">
            <el-table :data="planList" stripe ref="tableRef" height="300">
                <el-table-column>
                    <template #header>
                        <el-checkbox v-model="allChecked" @change="handleCheckAllChange"></el-checkbox>
                    </template>
                    <template #default="scope">
                        <el-checkbox v-model="checkedIds" :value="scope.row.processTypeId"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column  type="index" label="序号" width="80"></el-table-column>
                <el-table-column prop="typeCode" label="分类编号"></el-table-column>
                <el-table-column prop="typeName" label="分类名称"></el-table-column>
                <el-table-column prop="sort" label="排序"></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === true ? 'success' : 'danger'">{{ scope.row.status === true ? '启用' : '禁用' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="180"></el-table-column>
                <el-table-column prop="processTypeId" label="操作" fixed="right" width="140">
                    <template #default="scope">
                        <el-button type="text" @click="openDialog('edit', scope.row)">编辑</el-button>
                        <el-button type="text" @click="DeleteProductionPlanning(scope.row.processTypeId)">删除</el-button>
                        <!-- <el-button type="text" @click="GetByProductionPlanning(scope.row.processTypeId)">详情</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="batchDelete">批量删除</el-button>
        </div>
        <!-- 分页部分 -->
        <div class="demo-pagination-block">
            <el-pagination
                v-model:current-page="page.PageIndex"
                v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogType === 'add' ? '新增工序分类' : '编辑工序分类'"
            v-model="dialogVisible"
            :close-on-click-modal="false"
        >
                <el-form :model="formData" label-width="100px">
                    <el-form-item label="分类编号">
                        <el-input v-model="formData.typeCode" disabled placeholder="系统自动生成分类编号"></el-input>
                    </el-form-item>
                    <el-form-item label="分类名称">
                        <el-input v-model="formData.typeName"></el-input>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="formData.sort"></el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-switch v-model="formData.status"></el-switch>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="formData.remark" type="textarea"></el-input>
                    </el-form-item>
                </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveProcessType">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import router from '@/router';

// 定义 API URL 常量
const GET_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-read/api/GetProcess/GetProcessType';
const DELETE_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-write/api/Process/DelProcessType';
const ADD_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-write/api/Process/AddProcessType';
const UPDATE_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-write/api/Process/UpdateProcessType';

// 定义分页对象
const page = ref({
    PageIndex: 1,
    PageSize: 50,
});

// 定义分页总数
const total = ref({
    totalCount: 0,
    totalPage: 0,
});

// 模拟包装计划列表数据
const planList = ref([
    {
        "processTypeId": '',
        "typeCode": "",
        "typeName": "",
        "sort": '',
        "status": '',
        "isDel": '',
        "remark": ""
    }
]);

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);
// 选中的 ID 列表
const checkedIds = ref([]);

// 文件输入引用
const fileInput = ref(null);

// 对话框显示状态
const dialogVisible = ref(false);
// 对话框类型（add 或 edit）
const dialogType = ref('add');
// 表单数据
const formData = reactive({
    processTypeId: '',
    typeCode: '',
    typeName: '',
    sort: '',
    status: true,
    remark: ''
});

const GetProductionPlanning = () => {
    axios.get(GET_PROCESS_TYPE_URL, {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
        }
    }).then((res) => {
        planList.value = res.data.data.list;
        total.value.totalCount = res.data.data.totalCount;
        total.value.totalPage = res.data.data.totalPage;
        // 重置全选状态和选中的 ID 列表
        allChecked.value = false;
        checkedIds.value = [];
    }).catch((error) => {
        handleRequestError(error);
    });
};

const handleSizeChange = (val) => {
    page.value.PageSize = val;
    GetProductionPlanning();
};
const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    GetProductionPlanning();
};

onMounted(() => {
    GetProductionPlanning();
});

// 跳转编辑页面
const GetByProductionPlanning = (packagingPlanId) => {
    router.push({
        name: 'GetBYIddetailView',
        query: {
            packagingPlanId: packagingPlanId
        }
    });
    console.log(packagingPlanId);
};

// 处理请求错误
const handleRequestError = (error) => {
    if (error!== 'cancel') {
        console.error('请求错误:', error);
        ElMessage.error('请求失败，请检查网络或联系管理员');
    }
};

// 删除单条记录
const DeleteProductionPlanning = async (processTypeId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await axios.post(
                DELETE_PROCESS_TYPE_URL,
                {
                    processTypeIds: processTypeId.toString()
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        handleRequestError(error);
    }
};

// 处理全选
const handleCheckAllChange = (value) => {
    if (value) {
        checkedIds.value = planList.value.map(item => item.processTypeId);
    } else {
        checkedIds.value = [];
    }
    allChecked.value = value;
};

// 批量删除
const batchDelete = async () => {
    if (checkedIds.value.length === 0) {
        ElMessage.warning('请选择要删除的记录');
        return;
    }
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除选中的记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const ids = checkedIds.value.join(',');
            const response = await axios.post(
                DELETE_PROCESS_TYPE_URL,
                {
                    processTypeIds: ids
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('批量删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`批量删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        handleRequestError(error);
    }
};

// 打开对话框
const openDialog = (type, row = null) => {
    dialogType.value = type;
    if (type === 'add') {
        // 清空表单数据
        formData.processTypeId = '';
        formData.typeCode = '';
        formData.typeName = '';
        formData.sort = '';
        formData.status = true;
        formData.remark = '';
    } else if (type === 'edit') {
        // 反填数据
        formData.processTypeId = row.processTypeId;
        formData.typeCode = row.typeCode;
        formData.typeName = row.typeName;
        formData.sort = row.sort;
        formData.status = row.status;
        formData.remark = row.remark;
    }
    dialogVisible.value = true;
};

// 保存工序分类
const saveProcessType = async () => {
    let url = '';
    if (dialogType.value === 'add') {
        url = ADD_PROCESS_TYPE_URL;
    } else if (dialogType.value === 'edit') {
        url = UPDATE_PROCESS_TYPE_URL;
    }
    try {
        const response = await axios.post(url, formData);
        if (response.data.code === 200) {
            ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功');
            dialogVisible.value = false;
            GetProductionPlanning();
        } else {
            ElMessage.error(`${dialogType.value === 'add' ? '新增' : '编辑'}失败：${response.data.message}`);
        }
    } catch (error) {
        handleRequestError(error);
    }
};

const handleFileChange = (e) => {
    // 处理文件上传逻辑
    console.log('文件上传:', e.target.files);
};

</script>

<style scoped>
.table-container {
    max-height: 400px; /* 固定表格最大高度 */
    overflow-y: auto; /* 超出高度显示滚动条 */
    margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
    width: 100%; /* 表格宽度占满容器 */
}

/* 操作记录表格样式 */
.el-dialog .el-table {
    width: 100%;
}

.el-dialog .el-pagination {
    margin-top: 20px;
    text-align: right;
}
</style>    